"""
model name : 目标跟踪
file       : opencv.py
information:
    author : OuYang
    time   : 2025/7/19
"""

import cv2
import numpy as np


def show_image(img):
    """
    显示图片
    """
    cv2.imshow('img', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


class RectangleDrawer:
    def __init__(self, image):
        """
        初始化RectangleDrawer类
        :param image: 允许输入——图片路径或图片本身（cv:Mat格式）
        """

        self.src_image = image
        if isinstance(image, str):
            self.src_image = cv2.imread(image)

        if not isinstance(self.src_image, (cv2.Mat, np.ndarray)):
            raise TypeError('Error: 输入图片类型错误！！！')

        self.__copy_image = self.src_image.copy()  # 操作图片
        self.__drawing = False  # 是否正在绘制
        self.__ix, self.__iy, self.__fx, self.__fy = -1, -1, -1, -1  # 矩形起始点和结束点

        self.__window_name = "image"
        cv2.namedWindow(self.__window_name)
        cv2.setMouseCallback(self.__window_name, self._draw_rectangle_callback)

    def _draw_rectangle_callback(self, event, x, y, flags, param):
        """
        用于绘制的鼠标回调函数
        """
        if event == cv2.EVENT_LBUTTONDOWN:
            self.__drawing = True
            self.__ix, self.__iy, self.__fx, self.__fy = x, y, x, y
            self.__copy_image = self.src_image.copy()
        elif event == cv2.EVENT_MOUSEMOVE:
            temp_image = self.__copy_image.copy()
            if self.__drawing:
                self.__fx, self.__fy = x, y
                cv2.rectangle(temp_image, (self.__ix, self.__iy), (x, y), (0, 255, 0), 1)
            cv2.line(temp_image, (0, y), (self.__copy_image.shape[1], y), (0, 255, 255), 1)
            cv2.line(temp_image, (x, 0), (x, self.__copy_image.shape[0]), (0, 255, 255), 1)
            cv2.imshow(self.__window_name, temp_image)
        elif event == cv2.EVENT_LBUTTONUP:
            self.__drawing = False
            self.__fx, self.__fy = x, y
            cv2.rectangle(
                self.__copy_image,
                (self.__ix, self.__iy),
                (self.__fx, self.__fy),
                (0, 255, 0), 1
            )
            cv2.imshow(self.__window_name, self.__copy_image)
            self._calculate_rectangle_info()

    def _calculate_rectangle_info(self):
        """
        计算绘制的矩形信息
        """
        x1, y1 = min(self.__ix, self.__fx), min(self.__iy, self.__fy)
        x2, y2 = max(self.__ix, self.__fx), max(self.__iy, self.__fy)
        self.width, self.height = x2 - x1, y2 - y1
        self.center_x = x1 + self.width // 2
        self.center_y = y1 + self.height // 2

        print(f"Center: ({self.center_x}, {self.center_y}) Width: {self.width} Height: {self.height}")

    def get_rectangle_info(self):
        """
        获取矩形信息
        :return:
            dict: 包含中心位置、宽度和高度的字典
        """
        return {
            "center": (self.center_x, self.center_y),
            "width": self.width,
            "height": self.height
        }

    def run(self):
        while True:
            cv2.imshow(self.__window_name, self.__copy_image)
            if cv2.waitKey(1) & 0xFF == 27:
                break

        cv2.destroyAllWindows()


if __name__ == "__main__":
    image = np.zeros((800, 800, 3), np.uint8)
    drawer = RectangleDrawer(image)
    drawer.run()
